package com.wzapp.sitposture.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.management.OperatingSystemMXBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.lang.management.ManagementFactory;

public class MemDiskUtil {

    private static final Logger log = LoggerFactory.getLogger(MemDiskUtil.class);

    public static void main(String[] args)
    {
        JSONObject jsonObject = getMemInfo();
        log.info("=============" + jsonObject.toJSONString());
        JSONArray jsonArray = getDiskInfo();
        log.info("=============" + jsonArray.toJSONString());
    }

    public static JSONArray getDiskInfo()
    {
        File[] disks = File.listRoots();
        JSONObject jsonObject = null;
        JSONArray jsonArray = new JSONArray();

        for(File file : disks)
        {
            System.out.print(file.getPath() + "    ");
//            System.out.print("空闲未使用 = " + file.getFreeSpace() / 1024 / 1024 + "M" + "    ");// 空闲空间
//            System.out.print("已经使用 = " + file.getUsableSpace() / 1024 / 1024 + "M" + "    ");// 可用空间
//            System.out.print("总容量 = " + file.getTotalSpace() / 1024 / 1024 + "M" + "    ");// 总空间
//            System.out.println();

            jsonObject = new JSONObject();
            jsonObject.put("path", file.getPath());
            jsonObject.put("freeSpace", file.getFreeSpace() / 1024 / 1024);
            jsonObject.put("useSpace", file.getUsableSpace() / 1024 / 1024);
            jsonObject.put("totalSpace", file.getTotalSpace() / 1024 / 1024);

            jsonArray.add(jsonObject);
        }

        return jsonArray;
    }

    public static JSONObject getMemInfo()
    {
        OperatingSystemMXBean mem = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
//        System.out.println("Total RAM：" + mem.getTotalPhysicalMemorySize() / 1024 / 1024 + "MB");
//        System.out.println("Available　RAM：" + mem.getFreePhysicalMemorySize() / 1024 / 1024 + "MB");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("totalMem", mem.getTotalPhysicalMemorySize() / 1024 / 1024);
        jsonObject.put("availableMem", mem.getFreePhysicalMemorySize() / 1024 / 1024);

        return jsonObject;
    }
}
